package com.jielihaofeng.nio.c4;

import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.ArrayList;
import java.util.List;

import static com.jielihaofeng.nio.bytebuffer.ByteBufferUtil.debugRead;

/**
 * @description 非阻塞模式
 * @author Johnnie Wind
 * @date 2021/10/11 22:08
 */
@Slf4j
public class ServerNoBlocking {

    public static void main(String[] args) throws IOException {

        // 0. ByteBuffer
        ByteBuffer buffer = ByteBuffer.allocate(16);

        // 1. 创建服务器
        ServerSocketChannel ssc = ServerSocketChannel.open();
        ssc.configureBlocking(false); // 非阻塞模式
        // 2. 绑定端口
        ssc.bind(new InetSocketAddress(8080));

        // 3. 连接集合
        List<SocketChannel> channels = new ArrayList<>();
        while (true) {
            // 4. accept 建立与客户端的连接，SocketChannel 用来与客户端之间通信
//            log.debug("connecting...");
            SocketChannel sc = ssc.accept(); // 非阻塞，线程还会进行，如果连接没有建立，但sc是null
            if (sc != null) {
                log.debug("connected... {}", sc);
                sc.configureBlocking(false); // 将SocketChannel设置非阻塞模式
                channels.add(sc);

                for (SocketChannel channel : channels) {
                    // 5.接收客户端发送的数据
//                    log.debug("before read... {}", channel);
                    int read = channel.read(buffer);// 非阻塞方法，线程仍然会继续运行，没有读到数据，read 返回 0
                    if (read != 0) {
                        buffer.flip();
                        debugRead(buffer);
                        buffer.clear();
                        log.debug("after read... {}", channel);
                    }
                }
            }
        }

    }

}
